﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mvvm;
using System.Collections.ObjectModel;
using System.Windows.Data;
using System.ComponentModel;
using CodeIn.Core;

namespace CodeIn.Modules.Misc.CommandList {
	public class CommandListViewModel : BaseViewModel {
		private string filter;
		public string Filter {
			get { return filter; }
			set {
				filter = value;
				FirePropertyChanged("Filter");
				var source = CollectionViewSource.GetDefaultView(Commands);
				source.Filter = p => ((string)p).StartsWith(filter.Trim(), StringComparison.InvariantCultureIgnoreCase);
			}
		}

		public ObservableCollection<string> Commands { get; private set; }

		public string AssociatedCommands { get; private set; }
		public string AssociatedModule { get; private set; }
		public string Revision { get; private set; }
		public string Author { get; private set; }
		public string ShortDescription { get; private set; }
		public string LongDescription { get; private set; }

		public CommandListViewModel() {
			Commands = new ObservableCollection<string>();

			var source = CollectionViewSource.GetDefaultView(Commands);
			source.CurrentChanged += (s, e) => {
				if (source.CurrentPosition >= 0 && source.CurrentPosition < Commands.Count) {
					var cmd = (string)source.CurrentItem;
					var mod = ModuleManager.Instance.GetModuleFromCommand(cmd);

					AssociatedCommands = GetAssociatedCommands(mod.Infos.Commands);
					AssociatedModule = mod.Infos.Name;
					Revision = mod.Infos.Revision;
					Author = mod.Infos.Author;
					ShortDescription = mod.Infos.ShortDescription;
					LongDescription = mod.Infos.LongDescription;

					FirePropertyChanged("AssociatedCommands");
					FirePropertyChanged("AssociatedModule");
					FirePropertyChanged("Revision");
					FirePropertyChanged("Author");
					FirePropertyChanged("ShortDescription");
					FirePropertyChanged("LongDescription");
				}
			};

			ModuleManager.Instance.ModuleRegistered += (s, e) => {
				UpdateCommandList();
			};

			UpdateCommandList();
		}

		private void UpdateCommandList() {
			Commands.Clear();
			foreach (var cmd in ModuleManager.Instance.RegisteredCommands)
				Commands.Add(cmd);

			var source = CollectionViewSource.GetDefaultView(Commands);
			source.SortDescriptions.Clear();
			source.SortDescriptions.Add(new SortDescription());
		}

		private string GetAssociatedCommands(string[] commands) {
			string ret = "";
			if (commands.Length >= 1)
				ret += commands[0];
			for (int i = 1; i < commands.Length; i++)
				ret += ", " + commands[i];
			return ret;
		}
	}
}
